import json

from django import http
from datetime import datetime
from django.shortcuts import render

# Create your views here.
from django.views import View

from orders.models import Order
from houses.models import House

from AJZF.libs.response_code import RET
from AJZF.scripts.data_calculate import days


class Orderh(View):

    def post(self, request):
        dict = json.loads(request.body.decode())

        house_id = dict.get('house_id')  # 房屋id
        start_date = dict.get('start_date')  # 开始日期
        end_date = dict.get('end_date')  # 结束日期
        times = days(end_date, start_date)  # 预定时间

        format_pattern = '%Y-%m-%d'
        start_date = datetime.strptime(start_date, format_pattern)  # 时间类型转换
        end_date = datetime.strptime(end_date, format_pattern)

        house = House.objects.get(id=house_id)  # 房间对象

        if house.user == request.user:
            return http.JsonResponse({'errno': RET.DATAERR,
                                      'errmsg': '拒绝'})

        house_file = Order.objects.filter(house=house)

        for house_fi in house_file:
            end_time2 = house_fi.end_date  # 订单的房间结束时间

            start_time2 = house_fi.begin_date  # 订单的房间开始时间

            if start_date < start_time2 < end_date or start_time2 < start_date < end_time2:
                return http.JsonResponse({'errno': RET.DATAERR,
                                          'errmsg': '已定'})

        hou = House.objects.get(id=house_id)

        if times:
            if not hou.min_days < times and hou.max_days > times:
                return http.JsonResponse({'errno': RET.DATAERR,
                                          'errmsg': '空'})

        money = (times * house.price) / 100
        try:
            order = Order.objects.create(user=request.user,
                                         house=house,
                                         begin_date=start_date,
                                         end_date=end_date,
                                         days=times,
                                         house_price=house.price,
                                         amount=money)
        except Exception as e:
            return http.JsonResponse({'errno': RET.DATAERR,
                                      'errmsg': '创建订单失败'})

        return http.JsonResponse({"data": {"order_id": order.id},
                                  "errno": RET.OK,
                                  "errmsg": "OK"})

    def get(self,request):
        role = request.GET.get('role')

        list = []
        if role == 'custom':
            try:
                orders = Order.objects.filter(user=request.user)
            except Exception as e:
                return http.JsonResponse({'errno': RET.DATAERR,
                                          'errmsg': '数据库错误'})

            for order in orders:
                list.append({
                    "amount": order.amount,
                    "comment": order.comment,
                    "ctime": order.update_time,
                    "days": order.days,
                    "end_date": order.end_date,
                    "img_url": order.house.index_image_url,
                    "order_id": order.id,
                    "start_date": order.begin_date,
                    "status": order.status,
                    "title": order.house.title
                })


        elif role == 'landlord':
            user = request.user

            try:
                houses = House.objects.filter(user=user)
                for house in houses:
                    orders = Order.objects.filter(house=house)
                    for order in orders:
                        list.append({
                            "amount": order.amount,
                            "comment": order.comment,
                            "ctime": order.update_time,
                            "days": order.days,
                            "end_date": order.end_date,
                            "img_url": order.house.index_image_url,
                            "order_id": order.id,
                            "start_date": order.begin_date,
                            "status": order.status,
                            "title": order.house.title
                        })
            except Exception as e:
                return http.JsonResponse({'errno': RET.DATAERR,
                                          'errmsg': '数据库错误'})

        return http.JsonResponse({"data": {"orders":list},
                                  "errmsg": "OK","errno": RET.OK})





    def put(self,request):
        dict = json.loads(request.body.decode())
        action = dict.get('action')
        order_id = dict.get('order_id')  # 订单号
        reason = dict.get('reason')  # 拒单原因

        if not all([action, order_id]):
            return http.JsonResponse({'errno': RET.DATAERR,
                                      'errmsg': '缺少必传参数'})

        if action == 'accept':
            try:
                order = Order.objects.get(id=order_id)
            except Exception as e:
                return http.JsonResponse({'errno': RET.DATAERR,
                                          'errmsg': '数据库错误'})

            order.status = 'WAIT_COMMENT'
            if reason:
                order.comment = reason
            order.save()

        else:
            try:
                order = Order.objects.get(id=order_id)
            except Exception as e:
                return http.JsonResponse({'errno': RET.DATAERR,
                                          'errmsg': '数据库错误'})

            order.status = 'REJECTED'
            if reason:
                order.comment = reason
            order.save()

        return http.JsonResponse({ "errno": "0","errmsg": "OK"})


class Ordery(View):

     def put(self,request):
         dict = json.loads(request.body.decode())
         comment = dict.get('comment')
         order_id = dict.get('order_id')

         if not all([comment, order_id]):
             return http.JsonResponse({'errno': RET.DATAERR,
                                       'errmsg': '缺少必传参数'})

         try:
             order = Order.objects.get(id=order_id)
         except Exception as e:
             return http.JsonResponse({'errno': RET.DATAERR,
                                       'errmsg': '数据库错误'})

         try:
             # 保存评价信息
             order.comment = comment
             order.status = 'COMPLETE'
             order.save()

         except Exception as e:
             return http.JsonResponse({'errno': RET.DATAERR,
                                       'errmsg': '数据库错误'})

         house = order.house
         house.order_count += 1
         house.save()

         return http.JsonResponse({"errno": "0","errmsg": "OK"})



